package com.company.project.search.engine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.company.project.search.entity.Search;
import com.company.project.search.service.SearchEsService;
import com.company.project.search.util.OkHttpUtil;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//
public class E5 extends AbstractE implements Callback {

    private static final String url = "http://data.lilun.cn/Service/?logic=bookController&call=searchBookByColumnAndBookText";
    //超链接
    private static final String href = "http://f4e11c761cc55b777e10410d03ebcdf1.0dc4a5ff.libvpn.zuel.edu.cn/Service/?logic=PDFReaderController&call=readPDF&bookid=";

    private static final Headers headers = new Headers.Builder()
            .add("Referer", "http://data.lilun.cn/index_custom.html")
            .add("Accept", "*/*")
            .add("Accept-Encoding", "gzip, deflate")
            .add("Accept-Language", "zh-CN,zh;q=0.9")
            .add("Cache-Control", "max-age=0")
            .add("Connection", "keep-alive")
            .add("Content-Length", "271")
            .add("Cookie", "JSESSIONID=node0hoadgs7b2zck1u9ucv4pz1m5970076.node0; td_cookie=1546336738")
            .add("Host", "data.lilun.cn")
            .add("If-Modified-Since", "0")
            .add("Origin", "http://data.lilun.cn")
            .add("Content-Type", "application/x-www-form-urlencoded")
            .add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36")
            .build();

    @Override
    public void search(Param p) {
        p.engine = Engine.ID_E5;
        if (p.curPage != 0) return;
        RequestBody body = new FormBody.Builder()
                .add("page", String.valueOf(p.curPage))
                .add("pageSize", "20")
                .add("specialid", "769,313,314,315,327,415,416,419,422,423,424,425,426,427")
                .add("columnId", "769,313,314,315,327,415,416,419,422,423,424,425,426,427")
                .add("searchtext", p.keyword)
                .add("panel", "system")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(headers)
                .tag(p)
                .build();

        OkHttpUtil.getInstance().enqueue(request, this);
    }

    @Override
    public JSONArray provideCategory() {
        JSONArray list = new JSONArray();
        list.add(new Category("5-1", "中国共产党思想理论资源数据库"));
        list.add(new Category("5-0", "中国共产党思想理论资源数据库-Other"));
        return list;
    }

    private void parse(String json, Result result) {
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject jsonResult = jsonObject.getJSONObject("result");
        int total = jsonResult.getIntValue("total");
        Result.Header header = new Result.Header();
        header.engine = Engine.ID_E5;
        header.engineName = "中国共产党思想理论资源数据库";
        header.maxPage = total / 8;
        header.totalCount = total;
        result.headers = new HashSet<>();
        result.headers.add(header);

        JSONArray jsonArray = jsonResult.getJSONArray("html");

        List<Search> list = new ArrayList<>();
        for (Object o : jsonArray) {
            Search tto = Search.newInstance(Engine.ID_E5);
            Document html = Jsoup.parse(o.toString());
            Element listItem = html.getElementsByClass("list_item").first();
            String name = listItem.text();
            tto.setName(name);
            Element source = html.getElementsByTag("a").first();
            String sourceText = source.text();
            tto.setSource(sourceText);
            String sourceOnClick = source.attr("onclick");
            System.out.println(sourceOnClick);
            Pattern p = Pattern.compile("[A-Z]_([_|\\d]|[A-Z])+");
            Matcher m = p.matcher(sourceOnClick);
            if (m.find()) {
                String g = m.group();
                tto.setUrl(href.concat(g));
            }
            String date = html.getElementsByTag("span").first().text();
            tto.setCategory("5-1");
            tto.setPublishDate(date);
            list.add(tto);
        }
        result.list = list;
        if (callback != null) callback.callback(result);
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        System.out.println("E9响应失败");
    }

    @Override
    public void onResponse(@NotNull Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                Param p = (Param) call.request().tag();
                if (p != null) System.out.println("E5响应成功:" + (System.currentTimeMillis() - p.duration) + "ms");
                Result result = new Result(p);
                parse(json, result);
            }
        }
    }

    private static final class Holder {
        private static final AbstractE ins = new E5();
    }

    private E5() {

    }

    public static AbstractE getInstance() {
        return E5.Holder.ins;
    }

}
